package server;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.logging.Logger;

import sheduler.EmailTask;
import smtp.SmtpSender;

public class SenderServlet implements Servable {
	private SmtpSender ss;	
	private Server server;
	
	public SenderServlet(Server s) {
		this.ss = new SmtpSender();
		this.server = s;
	}

	@Override
	public void serve(Request request, Response response) {
		OutputStream output = response.getBodyStream();
		try {		
			output.write("<h1>Sending email status</h1>".getBytes());
			
			// Gather mail params from GET request string
			String emailFrom = request.getParam("email_from");
			String emailTo = request.getParam("email_to");
			String emailSubject = request.getParam("email_subject");
			String emailMessage = request.getParam("email_message");
			String emailDelayString = request.getParam("email_delay");
			int emailDelay = 0;
			try {
				emailDelay = Integer.parseInt(emailDelayString);
			}
			catch (NumberFormatException e) {
				Logger.getLogger(Server.LOG).severe("Delay should be integer: "+ emailDelayString);
				emailDelay = 0;
			}
			
			// Call helper class to send email
			try {
				//ss.sendMail(emailFrom, emailTo, emailSubject, emailMessage);
				output.write(("<p>Email sent successfully</p>").getBytes());
			} catch (Exception e) {
				output.write(("<p>" + e.getMessage() + "</p>").getBytes());
			}
			
			EmailTask task = new EmailTask(this.ss, emailFrom, emailTo, emailSubject, emailMessage, emailDelay);
			this.server.getManager().addTask(task);			
			
			// Add back link
			output.write("<a href=\"/\">Back</a>".getBytes());

		} catch (IOException e) {
			Logger.getLogger(Server.LOG).severe("Cannot serve Servlet");
		}		
	}

	@Override
	public String getContentType() {
		return "text/html";
	}

}
